package cn.laike.modules.dev.controller.api;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import cn.laike.common.utils.R;
import cn.laike.common.utils.XMLUtils;
import cn.laike.common.utils.mp.MpUtils;
import cn.laike.modules.dev.entity.ConfigEntity;
import cn.laike.modules.dev.service.ConfigService;
import cn.laike.modules.dev.utils.DevCacheUtils;
import cn.laike.modules.dev.utils.MpCacheUtils;
import cn.laike.modules.wechat.entity.WechatEntity;
import cn.laike.modules.wechat.service.WechatService;
import net.sf.json.JSONObject;

@RestController
@RequestMapping("/api/mp")
public class ApiMpController {

	@Autowired
    private WechatService wechatService;
	@Autowired
    private ConfigService configService;
	/**
	 * 1.授权事件接收URL http://182s163a59.imwork.net/admin/api/mp/login
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "auth_event_receive")
	public String auth_event_receive(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// <xml> <AppId><![CDATA[wx70db286ac68964ea]]></AppId>
		// <Encrypt><![CDATA[iU9KiZ3CwpBIiwXiRifTQhE4p1nsKQfCO3AiE03inYL2/QrL7DFD/WZhp0obstOT1jsSfBc5GgxSA//heMDc+BdJ3B44axoO7awqnW106t/7FHX8Q7z6fv4DASVIrh2nIaRHm4SGSJaBr8zuS7wYlbJwgXKP1+s/uLHkseZkOYFrOej1xoK7zLGM5vGly0PLgqMikETgT7FrqGPrreNTcx9r9exCM/YfmpMugTaLs+yN9XJMUoXgt60RHodH7Qirq8S4jjbbnJyAN4VZexsTciE7fpO7P2VDP4Z/gpgvmLVvsaat1Sn/cDvrHXmje+yJsbov3FgkVFjHwWCMXy5DI5B3kn2As5kbdMpEjlKJZtY0aNybzryOjBlkKnvQg7EFpXa96pFywDt4dnWzyBZjTox+SogHV/eCgDc0Odzi4oF6MCxC3MznuIWjSGCBrkUJXhBpi+D+mSsXrTs+niCzpg==]]></Encrypt></xml>
		StringBuffer stringBuffer = new StringBuffer();
		BufferedReader bReader = request.getReader();
		String line = "";
		while ((line = bReader.readLine()) != null) {
			stringBuffer.append(line);
		}
		try {
			if (stringBuffer.length() > 0) {
				System.out.println("授权事件接收URL");
				System.out.println(stringBuffer.toString());

				Map<String, String> xmlMap = XMLUtils.xml2Map(stringBuffer.toString());
 	 	 		if(xmlMap.containsKey("xml.Encrypt")){
 	 	 			String encrypt = xmlMap.get("xml.Encrypt");
 	 	 			xmlMap = MpUtils.wxBizMsgCrypt(encrypt);
 		 	 		if(xmlMap.containsKey("xml.InfoType")){
 		 	 			String infoType = xmlMap.get("xml.InfoType");
 		 	 			if(infoType.equals("component_verify_ticket")){	 //微信后台推送的ticket，此ticket会定时推送
 		 	 				String componentVerifyTicket = xmlMap.get("xml.ComponentVerifyTicket");
 		 	 				MpCacheUtils.setComponentVerifyTicket(componentVerifyTicket);
 		 	 				System.out.println("微信后台推送的ticket");
 		 	 			}else if(infoType.equals("authorized")){	 //推送 授权成功通知
 		 	 				System.out.println("授权成功通知");
 		 	 			}else if(infoType.equals("unauthorized")){	 //推送 取消授权通知
 		 	 				if(xmlMap.containsValue("xml.AuthorizerAppid")) {
 		 	 					String authorizerAppid = xmlMap.get("xml.AuthorizerAppid");
 	 		 	 				WechatEntity wechat = wechatService.getWechatEntity(authorizerAppid);
 	 		 	 				if(wechat != null && wechat.getId() != null && wechat.getId() > 0){
 	 		 	 					wechat.setStatus(0);
 	 			 	 				wechatService.insertOrUpdate(wechat);
 	 			 	 				MpCacheUtils.del("mp_wechat_" + authorizerAppid);
 	 		 	 				}
 		 	 				}
 		 	 				System.out.println("取消授权通知");
 		 	 			}else if(infoType.equals("updateauthorized")){	 //推送 授权更新通知
 		 	 				System.out.println("授权更新通知");
 		 	 			}
 		 	 		}
 	 	 		}
			}
			return "success";
		} catch (Exception e) {
			e.printStackTrace();
			return "success";
		}
	}

	
	/**
	 * 2.消息与事件接收URL
	 * http://182s163a59.imwork.net/api/mp/chat
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "chat")
 	public String chat(HttpServletRequest request, HttpServletResponse response) throws Exception {
 		StringBuffer stringBuffer = new StringBuffer();
 		BufferedReader bReader = request.getReader();
 		String line = "";
 		while ((line = bReader.readLine()) != null) {
 			stringBuffer.append(line);
 		}
 		try {
			if (stringBuffer.length() > 0) {
				System.out.println("授权事件接收URL");
				System.out.println(stringBuffer.toString());

				Map<String, String> xmlMap = XMLUtils.xml2Map(stringBuffer.toString());
 	 	 		if(xmlMap.containsKey("xml.Encrypt")){
 	 	 			//
 	 	 			String encrypt = xmlMap.get("xml.Encrypt");
 	 	 			xmlMap = MpUtils.wxBizMsgCrypt(encrypt);
 		 	 		if(xmlMap.containsKey("xml.Event")){
 		 	 			String event = xmlMap.get("xml.Event");
 		 	 			String userName = xmlMap.get("xml.ToUserName");
 		 	 			if(event.equals("weapp_audit_success")){	 //微信后台推送的ticket，此ticket会定时推送
 		 	 				System.out.println("审核通过");
 		 	 				WechatEntity wechat = wechatService.getWechatByUserName(userName);
 		 	 				wechat.setErrcode("4");
 		 	 				wechat.setErrmsg("ok");
 		 	 				wechatService.insertOrUpdate(wechat);
 		 	 			}else if(event.equals("weapp_audit_fail")){	 //推送 授权成功通知
 		 	 				System.out.println("审核不通过");
 		 	 				WechatEntity wechat = wechatService.getWechatByUserName(userName);
 		 	 				wechat.setErrcode("3");
 		 	 				wechat.setErrmsg(xmlMap.get("xml.Reason"));
 		 	 				wechatService.insertOrUpdate(wechat);
 		 	 			}
 		 	 		}
 	 	 		}
			}
			return "success";
		} catch (Exception e) {
			e.printStackTrace();
			return "success";
		}
 	}
	/**
	 * 引导用户授权登陆
	 * http://182s163a59.imwork.net/admin/api/mp/redirect?uid=1&auth_code=queryauthcode@@@TTQ1PnAzfD67Y8qt1_RDKv4r-aDxJbFpFBVYNDQn-odETBelH6RSYnhN91lesSM5uM412Dno4OM0Cie2oOyU1A&expires_in=7200
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/redirect")
	public R redirect(@RequestParam(value="uid",defaultValue="0")Long uid,
			HttpServletRequest request,HttpServletResponse response) throws IOException {
		String authorizationCode = request.getParameter("auth_code");
		String expires_in = request.getParameter("expires_in");
		System.out.println(uid);
		System.out.println(expires_in);
		String componentAccessToken = MpCacheUtils.getComponentAccessToken();
		JSONObject result = MpUtils.api_query_auth(componentAccessToken, authorizationCode);
		//{"authorization_info":{"authorizer_appid":"wx1e519a27efb281ee","authorizer_access_token":"17_GDTJN9KxSPCnfgquwa8t-JFANNwps3oK0aXL93GmtQnTwbyKRk9CNXhUeA5xUwGP6NGdkad46b1hqUjp60C3xlruRY0CTaQGU5ri6TtaEmZ_nPmbkTPz5bn5W2BkakXED2HXmK4m-MwifhGEOAJfAGDKWF","expires_in":7200,"authorizer_refresh_token":"refreshtoken@@@zw2C2rGVXGj2IlhRfwAjjmmWyOmL3FBgtn35clVQg5o","func_info":[{"funcscope_category":{"id":1}},{"funcscope_category":{"id":15}},{"funcscope_category":{"id":4}},{"funcscope_category":{"id":7}},{"funcscope_category":{"id":2}},{"funcscope_category":{"id":3}},{"funcscope_category":{"id":11}},{"funcscope_category":{"id":6}},{"funcscope_category":{"id":5}},{"funcscope_category":{"id":8}},{"funcscope_category":{"id":13}},{"funcscope_category":{"id":9}},{"funcscope_category":{"id":10}},{"funcscope_category":{"id":12}},{"funcscope_category":{"id":22}},{"funcscope_category":{"id":23}},{"funcscope_category":{"id":24},"confirm_info":{"need_confirm":0,"already_confirm":0,"can_confirm":0}},{"funcscope_category":{"id":26}},{"funcscope_category":{"id":27},"confirm_info":{"need_confirm":0,"already_confirm":0,"can_confirm":0}},{"funcscope_category":{"id":33},"confirm_info":{"need_confirm":0,"already_confirm":0,"can_confirm":0}},{"funcscope_category":{"id":35}},{"funcscope_category":{"id":44},"confirm_info":{"need_confirm":0,"already_confirm":0,"can_confirm":0}}]}}
		if(uid != null && uid > 0)
		if(result.containsKey("authorization_info")){
			if(result.containsKey("authorization_info")){
				JSONObject authorization_info = result.getJSONObject("authorization_info");
				String authorizerAppid = authorization_info.getString("authorizer_appid");
				WechatEntity wechat =  wechatService.getWechatEntity(authorizerAppid);
				if(wechat == null){
					wechat = new WechatEntity();
				}
				wechat.setCreateTime(new Date());
				wechat.setUid(uid);
				wechat.setAuthorizationAppid(authorizerAppid);
				wechat.setAuthorizerAccessToken(authorization_info.getString("authorizer_access_token"));
				wechat.setAuthorizerRefreshToken(authorization_info.getString("authorizer_refresh_token"));
				wechat.setStatus(1);
				result = MpUtils.api_get_authorizer_info(componentAccessToken, wechat.getAuthorizationAppid());
				if(result.containsKey("authorization_info")){
					JSONObject authorizer_info = result.getJSONObject("authorizer_info");
					if(result.containsKey("authorizer_info")){
						wechat.setNickName(authorizer_info.getString("nick_name"));
						wechat.setHeadImg(authorizer_info.getString("head_img"));
						wechat.setUserName(authorizer_info.getString("user_name"));
						wechat.setPrincipalName(authorizer_info.getString("principal_name"));

					}
				}
				wechatService.insertOrUpdate(wechat);
				MpCacheUtils.setAuthorizerAccessToken(authorizerAppid, wechat.getAuthorizerAccessToken());
				MpCacheUtils.del("mp_wechat_" + wechat.getAuthorizationAppid());
				
				ConfigEntity config = DevCacheUtils.getConfig(uid);
				if(config != null && config.getId() > 0){
					config.setAppId(wechat.getAuthorizationAppid());
					config.setName(wechat.getNickName());
					configService.insertOrUpdate(config);
			        DevCacheUtils.del("config_"+uid);
				}else{
					config = new ConfigEntity();
					config.setUid(uid);
					config.setAppId(wechat.getAuthorizationAppid());
					config.setName(wechat.getNickName());
			    	config.setCreateTime(new Date());
			        configService.insert(config);
			        DevCacheUtils.del("config_"+uid);
				}
				
			}
		}
		return R.ok();
	}

}
